/**
 * Created by yuanqiujuan on 2017/7/14.
 */
var _util = function(){
    if(this instanceof _util){
        return this;
    }else{
        return new _util();
    }
};

_util.prototype = {
    addEvent: function(dom, eventType, callback){
        if(dom.addEventListener){
            dom.addEventListener(eventType, callback)
        }else if(dom.attachEvent){
            dom.attachEvent('on' + eventType, callback)
        }else{
            dom['on' + eventType] = callback
        }
    },
    setAdaptive: function(a, callback){
        var c,
            f = document.documentElement,
            d = a.navigator.appVersion.match(/iphone/gi) ? a.devicePixelRatio : 1,
            w;

        function b() {
            if(f.getBoundingClientRect().width){
                w = f.getBoundingClientRect().width
            }else{
                w = f.getBoundingClientRect().right - f.getBoundingClientRect().left
            }
            a.rem = w / 10;
            f.style.fontSize = a.rem + "px";


            if(callback){
                callback()
            }
        }

        this.addEvent(a, "resize", function() {
            clearTimeout(c);
            c = setTimeout(b, 300)
        }, !1);

        this.addEvent(a, "pageshow", function(a) {
            a.persisted && (clearTimeout(c), c = setTimeout(b, 300))
        }, !1);

        f.setAttribute("data-dpr", d);

        b();
    },
    getScrollProp: function(prop){
        var a = 0,
            bodyScrollProp = 0,
            documentScrollProp = 0;

        if(document.body){
            bodyScrollProp = document.body[prop]
        }

        if(document.documentElement){
            documentScrollProp = document.documentElement[prop]
        }

        a = bodyScrollProp > documentScrollProp ? bodyScrollProp : documentScrollProp;

        return a;

    },
    getWindowHeight: function(){
        var windowHeight = 0;

        if(document.compatMode = "CSS1Compat"){
            windowHeight = document.documentElement.clientHeight
        }else{
            windowHeight = document.body.clientHeight
        }

        return windowHeight;
    },
    isInBottom: function(){
        if(this.getScrollProp("scrollTop") + this.getWindowHeight() == this.getScrollProp("scrollHeight")){
            return true;
        }

        return false;
    },
    getUrlParams: function(name){
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
            r = window.location.search.substr(1).match(reg);

        if(r != null){
            return decodeURIComponent(r[2])
        }else{
            return null;
        }
    },
    setGoogleAnalytics: function(id, callback){
        var i = id || 'UA-88841927-2';

        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
        ga('create', i, 'auto');

        if(callback){
            callback()
        }
    },
    googleEventAnalytics: function(cate, action, label){
        ga('send', {
            hitType: 'event',
            eventCategory: cate,
            eventAction: action,
            eventLabel: label
        });
    },
    getWebViewInter: function(fnName, livecall, callback, callbackName){
        var count = 0,
            count2 = 0,
            timer,
            timer2;

        if(callbackName){
            window[callbackName] = callback
        }else{
            window[fnName + "Callback"] = callback
        }

        timer = setInterval(function(){
            if(count < 10){
                run()
            }else{
                clearInterval(timer);
                alert("time out, try again later!");
            }
        }, 10);

        function run(){
            try{
                if(live || (window.webkit && window.webkit.messageHandlers)){
                    if(window.webkit && window.webkit.messageHandlers){
                        window.webkit.messageHandlers[fnName].postMessage(params)
                    }else{
                        livecall(live);
                        // live[fnName](params);
                    }

                    if(fnName === "configBack"){
                        window.backWindow = function() {
                            callback()
                        };
                    }else{

                        // timer2 = setInterval(function(){
                        //     alert("调用callback");
                        //     if(count2 > 10){
                        //         clearInterval(timer2)
                        //     }
                        //
                        //     if(!!window[fnName + "Callback"]){
                        //         clearInterval(timer2)
                        //     }
                        //
                        //     count2++;
                        // }, 10);
                    }

                    clearInterval(timer);
                    return true;
                }
            }catch (e){
                console.log(e)
            }

            count++;
        }

    },
    checkMobile: function(){
        var u = navigator.userAgent,
            os;

        var isPC = function(){
            var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
            var res = true;
            for (var v = 0;v<Agents.length;v++){
                if(u.indexOf(Agents[v])>0){
                    res = false;
                    break;
                }
            }
            return res;
        };

        if(u.indexOf('Android') > -1 || u.indexOf('Adr') > -1){
            os = "Android"
        }

        if(!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){
            os = "iOS"
        }

        if(isPC()){
            os = "PC"
        }

        return os;
    },
    is_lt_ios9: function(){
        var u = navigator.userAgent,
            os;

        if(u.match(/OS [5-8]_\d[_\d]* like Mac OS X/i)){
            return false;
        }

        return true;
    },
    createNode: function(tagName, attr, parent){
        var node = document.createElement(tagName);

        for(var i in attr){
            node.setAttribute(i, attr[i])
        }

        parent.appendChild(node)
    },
    createBranchIO: function(key){
        (function(b,r,a,n,c,h,_,s,d,k){if(!b[n]||!b[n]._q){for(;s<_.length;)c(h,_[s++]);d=r.createElement(a);d.async=1;d.src="https://cdn.branch.io/branch-latest.min.js";k=r.getElementsByTagName(a)[0];k.parentNode.insertBefore(d,k);b[n]=h}})(window,document,"script","branch",function(b,r){b[r]=function(){b._q.push([r,arguments])}},{_q:[],_v:1},"addListener applyCode autoAppIndex banner closeBanner closeJourney creditHistory credits data deepview deepviewCta first getCode init link logout redeem referrals removeListener sendSMS setBranchViewData setIdentity track validateCode trackCommerceEvent".split(" "), 0);
        branch.init(key, function(err, data) {});
    },
    openApp: function(params){
        var that = this,
            iframe,
            os = that.checkMobile(),
            timer;

        that.addEvent(params.el, params.eventType, function(){
            switch (true){
                case os === "Android" || (os === "iOS" && !params.isUniversalLink && that.is_lt_ios9()):
                    iframe = that.createNode("iframe", {
                        "src": params.appUrl,
                        "style": "display:none"
                    }, document.body);
                    break;
                case os === "iOS" && !params.isUniversalLink && !that.is_lt_ios9():
                    window.location.href = params.appUrl;
                    break;
                case os === "PC":
                    window.location.href = params.pcUrl;
                    break;
            }

            timer = setTimeout(function(){
                switch (os){
                    case "Android":
                        window.location.href = params.googlePlayUrl;
                        break;
                    case "iOS":
                        window.location.href = params.appStoreUrl;
                        break;
                    default:
                        window.location.href = params.pcUrl;
                        break;
                }

                document.body.removeChild(iframe);
            });
        });

        if(params.isUniversalLink){
            that.createBranchIO(params.universalLinkKey);

            branch.link(params.universalLinkParams, function(err, link){
                that.addEvent(params.el, params.eventType, function(){
                    window.location.href = link;
                });
            });
        }

        that.addEvent(document, "webkitvisibilitychange", function(){
            var tag = document.hidden || document.webkitHidden;

            if (tag) {
                clearTimeout(timer);
            }
        });

        that.addEvent(document, "pagehide", function(){
            clearTimeout(timer);
        });
    },
    scrollNews: function(params){
        var data = params.data,
            el = params.el,
            html = "",
            options = {
                transTime: 1
            };

        if(!params.transTime){
            params.transTime = options.transTime
        }

        for(var i = 0; i < data.length; i++){
            html += '<p class="menus">' + data[i] + '</p>'
        }

        el.innerHTML = html;

        function scroll() {
            var first = document.getElementsByClassName("menus")[0],
                height = first.scrollHeight;

            el.style.top = - height + "px";
            el.className = el.className.replace(" y-slide-stop ", "");

            setTimeout(function(){
                el.style.top = 0;
                el.className += " y-slide-stop ";
                el.removeChild(first);
                el.appendChild(first);
            }, params.transTime * 1000)
        }

        setInterval(function(){
            scroll()
        }, params.scrollInter * 1000)
    }
};